package com.test.ayi.service;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class BusinessService {
    private final Counter myCustomCounter;
    private final MeterRegistry meterRegistry;
    private final List<String> items = new ArrayList<>(); // 将列表作为成员变量

    // 通过构造函数注入 MeterRegistry
    public BusinessService(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        // 创建一个计数器
        this.myCustomCounter = Counter.builder("my.custom.counter")
                .description("A custom counter example")
                .tag("type", "business") // 可以添加标签
                .register(meterRegistry);
        
        // 在构造函数中注册 Gauge，只注册一次
        Gauge.builder("my.items.size", items, List::size)
                .description("Number of items in the list")
                .register(meterRegistry);
    }

    public void counter() {
        // 业务逻辑...
        // 增加计数器
        myCustomCounter.increment();
        // 或者增加特定值
        // myCustomCounter.increment(5);
    }
    public void gauge() {
        // 清空列表并添加新的随机数量的项
        items.clear();
        int randomSize = ThreadLocalRandom.current().nextInt(10);
        for (int i = 0; i < randomSize; i++) {
            items.add(String.valueOf(i));
        }
        System.out.println("Current items size: " + items.size());
    }



    @Timed(value = "business.operation.duration", description = "Time taken to perform business operation")
    public void performBusinessOperation() {
        // 模拟耗时操作
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}